<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\AreaManagement;
use addons\kuerp\model\Contacts;
use addons\kuerp\model\Customers as CustomerModel;
use addons\kuerp\model\CustomerFile;
use addons\kuerp\model\CustomerOther;
use addons\kuerp\model\DeliveryProduct;
use addons\kuerp\model\FormField;
use addons\kuerp\model\Message;
use addons\kuerp\model\OperationLog;
use addons\kuerp\model\Record;
use addons\kuerp\model\SeaOperation;
use addons\kuerp\model\Seastype;
use addons\kuerp\model\Staff;
use addons\kuerp\model\StaffCollect;
use addons\kuerp\model\StaffSignIn;
use addons\kuerp\model\AdminConfig;

use app\admin\controller\kuerp\Goods;
use app\admin\model\department\Admin;
use addons\kuerp\model\Admin as AdminModel;
use addons\kuerp\model\StaffMember;
use think\Db;
use think\Log;
use think\Exception;
use addons\kuerp\model\Delivery;

/**
 * 客户接口
 */
class Customers extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];
    protected $customerType = [];


    //获取select客户列表
    public function getSelectList()
    {
        $limit = input("limit/d", 20);
        $name = input('name');
        $id = input('id','');
        $where = [];
        if ($name) {
            $where['customer_name'] = ['like', "%{$name}%"];
        }
        if ($id !== '') {
            $where['id'] = $id;
        }
        $where['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];

        $list = CustomerModel::where($where)->with(['staff'])->field('id,customer_name,staff_member_id,follow_status,need_receive_account,address')->paginate($limit);
        $this->success('请求成功', $list);
    }


    //获取搜索员工列表
    public function getSearchStaffList()
    {
        $ids = Staff::getMyStaffIds();

        $staff = Staff::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->field('id,name,img,post')->select();
        $this->success('请求成功', $staff);
    }


    //获取客户列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        // $params['type'] = isset($params['type']) ? $params['type'] : 0;
        $where = FormField::updateWhereField(FormField::CUSTOMER_TYPE,$params);
        
        // if ($this->auth->is_sale) {
        //     // $wheres['customers.staff_member_id'] = ['in', [0, $this->auth->staff_member_id]];
        //     $where['customers.staff_member_id'] = ['exp', Db::raw(' in (0, '.$this->auth->staff_member_id.')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
        // }
        // //转为职员id
        // if ($this->auth->sale_users) {
        //     $where['customers.staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
        // } else {
        //     $where['customers.staff_member_id'] = ['exp', Db::raw(' =-1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
        // }

        if (isset($params['name']) && $params['name']) {//客户名称
            $where['customer_name|address|room'] = ['like', "%{$params['name']}%"];
        }
        if (isset($params['customertype']) && $params['customertype']) {//客户分类
            $where['customertype_id'] = $params['customertype'];
        }
        if (isset($params['level']) && $params['level']) {//客户等级
            $where['customerlevel_id'] = $params['level'];
        }
        // if (isset($params['source']) && $params['source']) {//客户来源
        //     $where['source'] = $params['source'];
        // }
        if (isset($params['follow']) && $params['follow']) {//跟进状态
            $where['follow_status'] = $params['follow'];
        }
        if (isset($params['createtime']) && $params['createtime']) {//创建时间
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'time');
            $where['customers.createtime'] = ['between', $times];
        }
        $order = 'id desc';
        if (isset($params['sortid']) && $params['sortid']) {
            switch ($params['sortid']) {
                case 1://名称正序
                    $order = 'customer_name asc';
                    break;
                case 2://名称倒序
                    $order = 'customer_name desc';
                    break;
                case 3://创建时间正序
                    $order = 'customers.createtime asc';
                    break;
                case 4://创建时间倒序
                    $order = 'customers.createtime desc';
                    break;
                // case 5://下次跟进时间正序
                //     $order = 'next_time asc';
                //     break;
                // case 6://下次跟进时间倒序
                //     $order = 'next_time desc';
                //     break;
            }
        }

        // if (isset($params['next_time']) && $params['next_time']) {//下次联系时间
        //     $next_time = $params['next_time'];
        //     $next_time = explode(',', $next_time);
        //     $where['next_time'] = ['between', [$next_time[0], $next_time[1]]];
        // }

        // $whereStaff = [];
        // //0全部 1 我负责  2 我参与  11 我下属负责
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['staff_member_id'] = $params['staff_id'];
        } else {
            $staff_id = $this->auth->id;
            $type = $params['type'] ?? 0;
            if ($type == 1) {//我的客户
                $whereStaff['staff_member_id'] = ['exp', Db::raw(' ='. $this->auth->staff_member_id.'  OR FIND_IN_SET('.$staff_id.',collaborator)')];
            } elseif ($type == 11) {//下属负责的客户
                $sale_users = $this->auth->sale_users;
                if (in_array($this->auth->staff_member_id, $sale_users)) {
                    $sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
                }
                $whereStaff['staff_member_id'] = ['in', $sale_users];
            } elseif ($type == 2) {//我参与的客户
                $whereStaff = function ($query) use ($staff_id) {
                    $query->where(Db::raw('FIND_IN_SET('.$staff_id.',collaborator)'));
                };
            }else{
                $whereStaff['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$staff_id.',collaborator)')];
                // $whereStaff = function ($query) use ($staff_id) {
                //     $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                //         ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                //         ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
                // };
            }

        }
        // if (isset($params['contract_status']) && $params['contract_status'] !== '') {
        //     $where['contract_status'] = $params['contract_status'];
        // }
        if (isset($params['is_import'])) {
            if ($params['is_import'] == 1) {
                $where['lng'] = 0;
            } elseif ($params['is_import'] == 2) {
                $where['lng'] = ['neq', 0];
            }
        }
        if (isset($params['prov']) && !empty(trim($params['prov']))) {//省市区筛选
            $prov = trim($params['prov']);
            $city = trim($params['city']);
            $area = trim($params['area']);
            $cityinfo = $prov.$city.$area;
            if (empty($city)) {
                $where['address'] = ['like', "%{$prov}%"];
            } elseif (empty($area)) {
                $where['address'] = ['like', "%{$city}%"];
            } else {
                $where['address'] = ['like', "%{$cityinfo}%"];
            }
        }
        $where['customers.status'] = '1';
        if(isset($params['id_list'])){//日志 查询id列表
            $where=[];
            $where['customers.id']=['in',explode(',',$params['id_list'])];
        }

        $list = CustomerModel::where($where)->where($whereStaff)->with([
            'saler',
            'customertype','customerlevel',
        ])->order($order)->paginate($limit);
        foreach ($list as $row) {
            $row->getRelation('customerlevel')->visible(['name']);
            $row->getRelation('customertype')->visible(['type_name']);
            $row->getRelation('saler')->visible(['name']);
        }
        $list = $list->toArray();
        $data = $list['data'];
        //获取头像
        $admins = [];
        $salesStatics = [];
        $stafflist = [];
        if ($data) {
            $customersids = array_column($data, 'id');
            $staffids = array_column($data, 'staff_member_id');
            $stafflist = StaffMember::where('id', 'in', $staffids)->column('admin_id', 'id');
            $adminids = array_values($stafflist);
            $admins = AdminModel::where('id', 'in', $adminids)->column('avatar', 'id');
            //获取消费金额 回款金额
            $salesStatics = Db::name('kuerp_goods_sales')->where('customers_id', 'in', $customersids)->group('customers_id')->column('sum(real_money) as sale_money,sum(pay_money) as pay_money', 'customers_id');
        }
        
        foreach ($data as $k => $v) {
            if ($v['staff_member_id'] == $this->auth->staff_member_id ||
                in_array($v['staff_member_id'],$this->auth->sale_users) || in_array($this->auth->id, explode(',', $v['collaborator']))) {
                $v['is_operation'] = 1;
            } else {
                $v['is_operation'] = 0;
            }
            $v['last_follow_time'] = $v['last_follow_time'] ? date('Y-m-d H:i') : '';
            $avatar = $admins[$stafflist[$v['staff_member_id']]] ?? '';
            $v['saler']['avatar'] = cdnurl($avatar, true);
            $v['sale_money'] = $salesStatics[$v['id']]['sale_money'] ?? 0;
            $v['pay_money'] = $salesStatics[$v['id']]['pay_money'] ?? 0;
            $v['unback_money'] = round($v['sale_money'] - $v['pay_money'], 2);
            // if($v['contract_status']==1){
            //     $v['follow'] = '已成交';
            // }else{
            //     $v['follow'] = '未成交';
            // }
            $data[$k] = $v;
        }

        $this->success('请求成功', [
            'total' => $list['total'],
            'per_page' => $list['per_page'],
            'current_page' => $list['current_page'],
            'last_page' => $list['last_page'],
            'data' => $data
        ]);
    }


    //获取公海客户列表
    public function getSeasList()
    {
        $this->success('请求成功', [
            'total' => 0,
            'per_page' => 1,
            'current_page' => 1,
            'last_page' => 1,
            'data' => []
        ]);
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $where= FormField::updateWhereField(FormField::CUSTOMER_TYPE,$params);

        if (isset($params['name']) && $params['name']) {//客户名称
            $where['name|subname'] = ['like', "%{$params['name']}%"];
        }
        if (isset($params['level']) && $params['level']) {//客户星级
            $where['level'] = $params['level'];
        }
        if (isset($params['source']) && $params['source']) {//客户来源
            $where['source'] = $params['source'];
        }
        if (isset($params['follow']) && $params['follow']) {//跟进状态
            $where['follow'] = $params['follow'];
        }
        if (isset($params['createtime']) && $params['createtime']) {//跟进状态
            $createtime = $params['createtime'];
            $where['createtime'] = ['between', setTimes($createtime,'time')];
        }
        $order = 'id desc';
        if (isset($params['sortid']) && $params['sortid']) {//排序
            switch ($params['sortid']) {
                case 1://名称正序
                    $order = 'name asc';
                    break;
                case 2://名称倒序
                    $order = 'name desc';
                    break;
                case 3://创建时间正序
                    $order = 'createtime asc';
                    break;
                case 4://创建时间倒序
                    $order = 'createtime desc';
                    break;
                case 5://下次跟进时间正序
                    $order = 'next_time asc';
                    break;
                case 6://下次跟进时间倒序
                    $order = 'next_time desc';
                    break;
            }
        }

        if (isset($params['next_time']) && $params['next_time']) {//下次联系时间
            $next_time = $params['next_time'];
            $next_time = explode(',', $next_time);
            $where['next_time'] = ['between', [$next_time[0], $next_time[1]]];
        }
        if (isset($params['is_chengjiao']) && $params['is_chengjiao'] == 1) {
            $where['contract_status'] = 1;
        }
        if (isset($params['prov']) && !empty(trim($params['prov']))) {//省市区筛选
            $prov = trim($params['prov']);
            $city = trim($params['city']);
            $area = trim($params['area']);
            if (empty($city)) {
                $where['address|address_detail'] = ['like', "%{$prov}%"];
            } elseif (empty($area)) {
                $where['address|address_detail'] = ['like', "%{$city}%"];
            } else {
                $where['address|address_detail'] = ['like', "%{$area}%"];
            }
        }

        //公海权限
        $rules=Staff::getStaffRule('seas');
        $whereStaff = function ($query) use ($rules) {
            foreach ($rules as $rule) {
                $query->whereOr(['seas_id' => ['like', "%,{$rule},%"]]);
            }
        };
        $where['is_seas'] = 1;
        $list = CustomerModel::where($where)->where($whereStaff)->where('owner_staff_id is null or owner_staff_id = 0');
        $list = $list->with([
            'ownerStaff',
            'contractTotal',
            'receivablesTotal',
            'contacts'
        ])->field('id,type,name,address,last_time,owner_staff_id,level,follow,lng,lat,address')->order($order)->paginate($limit)->toArray();
        $data = $list['data'];

        $this->success('请求成功', [
            'total' => $list['total'],
            'per_page' => $list['per_page'],
            'current_page' => $list['current_page'],
            'last_page' => $list['last_page'],
            'data' => $data
        ]);
    }

    //查重客户名称
    public function selectName()
    {
        $name = input('name');
        if (CustomerModel::where(['name' => $name])->find()) {
            $this->error('客户名称已存在');
        }
        $this->success('当前客户名称可使用');
    }

    //获取区域列表
    public function getSeastypeList()
    {
        $seasIds=Staff::getStaffRule('seas');
        $seastype = Seastype::where(['id'=>['in',$seasIds]])->select();
        $this->success('请求成功', $seastype);
    }

    public function getcustomerCodes()
    {
        $this->success('请求成功', ['code' => $this->getCodes('', 1)]);
    }

    //新增客户
    public function addCustomer()
    {
        $params = $this->request->post();
        if (empty($params['customer'])) {
            $this->error('客户信息不能为空');
        }
        $result = FormField::checkFields(FormField::CUSTOMER_TYPE,$params['customer']);
        if ($result !== true) {
            $this->error($result);
        }
        $customer = $params['customer'];
        // 表单验证
        if (($result = $this->kuerpValidate($customer, get_class(),'create')) !== true) {
            $this->error($result);
        }
        if(empty($customer['connet_name'])){
            $this->error('请填写联系人');
        }
        $customer['account_time'] = strtotime($customer['account_time']);
        $customer['need_receive_account'] = round(((float)$customer['receive_account']-(float)$customer['opening_prepayment']),4);
        if (!empty($customer['area_id'])) {
            $areainfo = Db::name('area')->find($customer['area_id']);
            $customer['mergename'] = str_replace('中国,', '', $areainfo['mergename']);
        }
        if(Db::name('kuerp_customers')->where(['customer_code'=>trim($customer['customer_code'])])->find()){
            $this->error('客户编号已占用');
        }
        if ($this->auth->is_sale && $this->auth->staff_member_id) {
            $customer['staff_member_id'] = $this->auth->staff_member_id;
        }
        //判断客户名称是否重复
        $count = Db::name('kuerp_customers')->where(['customer_name' => $customer['customer_name'], 'staff_member_id' => $customer['staff_member_id'], 'status' => '1'])->count();
        if ($count) {
            $this->error($customer['customer_name'].'客户已存在');
        }
        $result = false;
        Db::startTrans();
        try {
            $customer['createtime'] = time();
            $customer['updatetime'] = time();
            $customer['collaborator'] = $params['reminds_id'];
            $customer['lng'] = $customer['address_lng'];
            $customer['lat'] = $customer['address_lat'];
            unset($customer['address_lat'],$customer['address_lng']);
            $result = Db::name('kuerp_customers')->insertGetId($customer);
            $business_type = 5;
            if($customer['need_receive_account']>0){//应收
                Db::name('kuerp_writeoff_source')->insert([
                    'purchase_type' => 5,
                    'type' => 3,
                    'customers_id' => $result,
                    'purchase_code' => $customer['customer_code'],
                    'purchase_time' => $customer['account_time'],
                    'price' => $customer['need_receive_account'],
                    'write_off' => $customer['need_receive_account'],
                    'remark' => $customer['note'],
                ]);
            }else if($customer['need_receive_account']<0){//预收
                Db::name('kuerp_writeoff_source')->insert([
                    'purchase_type' => 6,
                    'type' => 3,
                    'customers_id' => $result,
                    'purchase_code' => $customer['customer_code'],
                    'purchase_time' => $customer['account_time'],
                    'price' => -$customer['need_receive_account'],
                    'write_off' => -$customer['need_receive_account'],
                    'remark' => $customer['note'],
                ]);
                $business_type = 6;
            }
            Db::name('kuerp_sales_payment_log')->insert([
                'customers_id' => $result,
                'business_type' => $business_type,
                'bill_time' => $customer['account_time'],
                'bill_code' => $customer['customer_code'],
                'give_money' => $customer['need_receive_account'],
            ]);

            Db::name('kuerp_customers_user')->insert([
                'customers_code'=>$customer['customer_code'],
                'sid'=>$result,
                'first_connect_name'=>$customer['connet_name'],
                'first_connect_mobile'=>$customer['customer_mobile'],
                'first_connect_phone'=>'',
                'qq_wx_email'=>'',
                'connect_address'=>'',
                'is_first'=>1,
                'createtime' => time(),
                'updatetime' => time(),
            ]);
            if ($this->auth->parentids && !in_array(2, $this->auth->group_ids)) {
                $content = $this->auth->nickname . "刚刚新建了客户《{$customer['customer_name']}》,请您审阅！";
                foreach ($this->auth->parentids as $k=>$v){
                    Message::addMessage(Message::CUSTOMER_TYPE, $result, $v, $this->auth->id, $content);
                }
            }
            //发送通知
            $collaborator = explode(',', $params['reminds_id']);
            $content = $this->auth->nickname . "刚刚将您添加为客户《{$customer['customer_name']}》的协作人，请知悉";
            foreach ($collaborator as $v) {
                Message::addMessage(Message::CUSTOMER_TYPE, $result, $v, $this->auth->id, $content);
            }
//            $customerId = CustomerModel::createCustomer($params['customer']);
//            if(isset($params['customer']['mobile']) && $params['customer']['mobile']){
//                $retC = array(
//                    'customer_id'=>$customerId,
//                    'is_major'=>1,
//                    'region'=>1,
//                    'name'=>$params['customer']['name'],
//                    'mobile'=>$params['customer']['mobile'],
//                    'next_time'=>date('Y-m-d H:i:s'),
//                );
//                Contacts::createContacts($retC);
//            }
//            $content = $this->auth->name . "刚刚新建了客户《{$params['customer']['name']}》,请您审阅！";
//            Message::addMessage(Message::CUSTOMER_TYPE, $customerId, $params['reminds_id'], $this->auth->id, $content);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('新增客户成功',array('id'=>$result));
        }
    }

    public function getAddressProvince()
    {
        $address = input('address');
        $this->success('请求成功', AreaManagement::whereAddressProvince($address));
    }

    public function getAreaManagement()
    {
        $this->success('请求成功', AreaManagement::where([])->select());
    }

    //编辑客户
    public function editCustomer()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户信息不存在');
        }
        // 表单验证
        if (($result = $this->kuerpValidate($params, get_class(),'edit')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CUSTOMER_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $params['lng'] = $params['address_lng'];
            $params['lat'] = $params['address_lat'];
            $params['customer_name'] = $params['name'];
            $params['room'] = $params['room'] ?? '';
            $params['note'] = $params['note'] ?? '';
            unset($params['address_lng'],$params['address_lat'],$params['name']);
            $result = CustomerModel::updateCustomer($params);
            if(isset($param['customer_mobile']) && $params['customer_mobile']){
                Contacts::where(array('sid'=>$id,'is_first'=>1))->update(array(
                    'first_connect_name'=>$params['connet_name'],
                    'first_connect_mobile'=>$params['customer_mobile'],
                    'updatetime'=>time(),
                    ));
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改客户成功');
    }

    //合并客户
    public function mergeCustomer()
    {
        $new_id = input('id');
        $old_id = input('old_id');
        $contacts_id = input('contacts_id');
        $params = input('data/a');
        $params['id'] = $new_id;
        CustomerModel::updateCustomer($params);
        //合并联系人
        Contacts::where(['customer_id' => $old_id])->update(['customer_id' => $new_id]);
        //合并合同
        \addons\kuerp\model\Contract::where(['customer_id' => $old_id])->update(['customer_id' => $new_id]);
        //合并费用
        \addons\kuerp\model\Consume::where(['customer_id' => $old_id])->update(['customer_id' => $new_id]);
        //合并回款
        \addons\kuerp\model\Receivables::where(['customer_id' => $old_id])->update(['customer_id' => $new_id]);
        //合并任务
        \addons\kuerp\model\Event::where(['customer_id' => $old_id])->update(['customer_id' => $new_id]);

        //删除旧用户
        CustomerModel::destroy($old_id);

        Contacts::where(['customer_id' => $new_id])->update(['is_major'=>0]);
        Contacts::where(['id' => $contacts_id])->update(['is_major'=>1]);
        Message::setRead(Message::CUSTOMER_TYPE,$old_id);
        $this->success('合并成功');
    }

    //获取合并客户详情
    public function getMergeCustomerDetail()
    {
        $ids = input('ids');
        if (empty($ids)) {
            $this->error('参数不能为空');
        }
        $ids = explode(',', $ids);
        $customers = CustomerModel::where(['id' => ['in', $ids]])->select();
        $customers=collection($customers)->toArray();
        if(empty($customers)){
            $this->error('用户不存在');
        }
        foreach ($customers as $k=>$c) {
            $customers[$k] = CustomerOther::getOther($c);
        }
        $detail = [];
        foreach ($customers as $v) {
            foreach ($v as $key => $value) {
                if($value === null){
                    $detail[$key]=[];
                    continue;
                }
                if($key == 'name'){
                    $detail[$key][] = ['id'=>$v['id'],'name'=>$value];
                }elseif($key == 'address'){
                    $detail[$key][]=['name'=>$value,'lat'=>$v['lat'],'lng'=>$v['lng'],'address_detail'=>$v['address_detail']];
                }else{
                    $detail[$key][] = $value;
                }
            }
        }
        $detail['parent_id']=CustomerModel::where(['id'=>['in',$detail['parent_id']]])->field('id,name')->select();
        $contacts=Contacts::where(['customer_id'=>['in',$ids]])->field('id,name')->select();
        $detail['contacts']=$contacts;

        $this->success('请求成功', $detail);
    }

    //获取子公司
    public function getLowerCustomer()
    {
        $id = input('id');
        $customers = CustomerModel::where(['parent_id' => $id])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->select();

        $this->success('请求成功', $customers);
    }

    // 是否可以查看客户
    public function isShowCustomer()
    {
        $id = input('id');
        $customer = CustomerModel::where(['id' => $id])->find();
        if (empty($customer)) {
            $this->error('信息不存在');
        }
        $customer = $customer->toArray();
        if ($customer['owner_staff_id'] == $this->auth->id ||
            in_array($customer['owner_staff_id'], Staff::getLowerStaffId()) ||
            in_array($this->auth->id, explode(',', $customer['rw_staff_id'])) ||
            in_array($this->auth->id, explode(',', $customer['ro_staff_id']))

        ) {
            $this->success('请求成功', ['is_show' => 1]);
        }

        $this->success('请求成功', ['is_show' => 0]);
    }
    //客户详情
    public function customerDetail()
    {
        $id = input('id');
        $lng = input('lng', 0);
        $lat = input('lat', 0);
        $customer = CustomerModel::where(['customers.id' => $id])->with([
            'saler',
            'customertype',
            'customerlevel',
        ])->find();
        if (empty($customer)) {
            $this->error('信息不存在');
        }
        $customer = $customer->toArray();
        if ($customer['staff_member_id'] == $this->auth->staff_member_id || in_array($customer['staff_member_id'],$this->auth->sale_users) || in_array($this->auth->id, explode(',', $customer['collaborator']))) {
            $customer['operation'] = 'update';//修改权限
            $customer['is_operation'] = 1;     
        } else {
            $customer['operation'] = 'read';//只读权限
            $customer['is_operation'] = 0;
        }
        if ($this->auth->staff_member_id > 0 && $customer['staff_member_id'] != $this->auth->staff_member_id && !in_array($customer['staff_member_id'],$this->auth->sale_users) && !in_array($this->auth->id, explode(',', $customer['collaborator']))) {
            $this->error('抱歉，您没有权限查看该客户信息');
        }
        //获取消费金额 回款金额
        $customerStatics = Db::name('kuerp_goods_sales')->where('customers_id', $id)->field('sum(real_money) as sale_money,sum(pay_money) as pay_money,sum(back_money) as back_money')->find();
        $customer['sale_money'] = round($customerStatics['sale_money'] ?? 0, 2);
        $customer['pay_money'] = round($customerStatics['pay_money'] ?? 0, 2);
        $customer['back_money'] = round($customerStatics['back_money'] ?? 0, 2);
        $customer['debt_money'] = round($customer['sale_money'] - $customerStatics['pay_money'], 2);
        //获取负责人信息 部门信息
        $staffMember = Db::name('kuerp_staff_member')->field('id,name,admin_id')->find($customer['staff_member_id']);
        // $admin_info = Db::name('admin')->field('id,avatar,nickname')->find($staffMember['admin_id']);
        $department = (new Admin())->getDepartments($staffMember['admin_id']);
        $customer['staff'] =[
            'id'=>$staffMember['id'],
            'name' => $staffMember['name'],
            // 'nickname' => $admin_info['nickname'],
            'department' => implode('、',array_column($department, 'name'))
        ];

        $customer['last_follow_time'] = $customer['last_follow_time'] ? date('Y-m-d H:i') : '';
        //经纬度
        if (empty($customer['lng']) && !empty($customer['address'])) {
            $address = (strpos($customer['address'], '市') === false && !empty($customer['mergename']) ? str_replace(',', '', $customer['mergename']) : '' ) . $customer['address'];
            $map_key= AdminConfig::getConfigValue('map_key','wechat');
            if(empty($map_key)){
                $this->error('腾讯地图key未设置，请联系管理员设置！');
            }
            $address = urlencode($address);
            try{
                $url="https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key={$map_key}";
                $result=file_get_contents($url);
                Log::write('map---'.$result);
                $result=json_decode($result,true);
                if ($result['status']==0) {
                    $customer['lng']=$result['result']['location']['lng'];
                    $customer['lat']=$result['result']['location']['lat'];
                    CustomerModel::where(['id' => $id])->update(['lng'=>$customer['lng'],'lat'=>$customer['lat']]);
                }
            } catch (\Exception $e) {
                Log::write('map---获取位置报错：'.$e->getMessage());
            }
        }
        $customer['distance'] = 0;
        $customer['distance_num'] = 0;
        $max_distance = config('site.sign_max_distance');
        $customer['max_distance'] = $max_distance;
        if ($lng && $customer['lng']) {
            $customer['distance_num'] = getdistance($lng, $lat, $customer['lng'], $customer['lat']);
            $customer['distance'] = float_number($customer['distance_num']);
        }
                
        // if ($customer['owner_staff_id'] == $this->auth->id ||
        //     in_array($customer['owner_staff_id'],Staff::getLowerStaffId()) ||
        //     in_array($this->auth->id, explode(',', $customer['rw_staff_id'])) ) {
        //     $customer['operation'] = 'update';//修改权限
        //     $customer['is_operation'] = 1;
        // } else {
        //     $customer['operation'] = 'read';//只读权限
        //     $customer['is_operation'] = 0;
        // }
        $customer['is_collect'] = 0;//StaffCollect::isCollect(StaffCollect::CUSTOMER_TYPE, $customer['id']) ? 1 : 0;
        $customer['name'] = $customer['customer_name'];

        // $customer = CustomerOther::getOther($customer);
        //发货数量
        $customer['delivery_num'] = 0;
        $customer['collaborator'] = Db::name('admin')->whereIn('id', $customer['collaborator'])->field('id,nickname as name,avatar as img')->select();
        // $delivery = Delivery::where(['customer_id'=>$id])->column('id');
        // if($delivery){
        //     $customer['delivery_num'] =DeliveryProduct::where(array('delivery_id'=>array('in',$delivery)))->sum('number');
        // }

        Message::setRead(Message::CUSTOMER_TYPE, $id, $this->auth->id);
        $this->success('请求成功', $customer);
    }


    //移入公海
    public function moveSeas()
    {
        $id = input('id');
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户不存在');
        }
        Db::startTrans();
        try {
            CustomerModel::moveSeas($id);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('放入成功');
    }
    //批量移入公海
    public function batchMoveSeas()
    {
        $ids = input('ids');
        if(empty($ids)){
            $this->error('参数为空');
        }
        $ids=explode(',',$ids);
        $row = CustomerModel::where(['id' => ['in',$ids]])->select();
        if (empty($row)) {
            $this->error('客户不存在');
        }
        Db::startTrans();
        try {
            foreach ($ids as $id){
                CustomerModel::moveSeas($id);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('放入成功');
    }


    //转移客户
    public function transfer()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        if (empty($staff_id)) {
            $this->error('参数错误');
        }
        $staff = Staff::get($staff_id);
        if (empty($staff)) {
            $this->error('接收对象不存在');
        }
        //, 'owner_staff_id' => $this->auth->id
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户不存在');
        }
        try {
            CustomerModel::transfer($id, $staff_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('转移成功');
    }


    //批量转移客户
    public function batchTransfer()
    {
        $ids = input('ids');
        $staff_id = input('staff_id');
        if(empty($ids)){
            $this->error('参数为空');
        }
        $ids=explode(',',$ids);
        $row = CustomerModel::where(['id' => ['in',$ids]])->select();
        if (empty($row)) {
            $this->error('客户不存在');
        }
        Db::startTrans();
        try {
            foreach ($ids as $id){
                CustomerModel::transfer($id, $staff_id);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('放入成功');
    }

    //领取公海客户
    public function receive()
    {
        $customer_id = input('customer_id');
        $where = ['owner_staff_id' => 0];
        if ($customer_id) {
            $where['id'] = $customer_id;
        }
        $customers = CustomerModel::where($where)->count();
        if ($customers == 0) {
            $this->error('公海内暂无客户');
        }
        try {
            $id = CustomerModel::receive($customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('领取成功', ['id' => $id]);
    }


    //重点关注客户
    public function collect()
    {
        $customer_id = input('customer_id');
        try {
            StaffCollect::addCollect(StaffCollect::CUSTOMER_TYPE, $customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('重点关注成功');
    }


    //取消重点关注
    public function cancelCollect()
    {
        $customer_id = input('customer_id');
        try {
            StaffCollect::cancel(StaffCollect::CUSTOMER_TYPE, $customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('取消重点关注成功');
    }


    //重点关注客户列表
    public function collectList()
    {
        $limit = input("limit/d", 10);
        $ids = StaffCollect::where(['staff_id' => $this->auth->id, 'relation_type' => 1])->column('relation_id');
        $list = CustomerModel::where(['id' => ['in', $ids]])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order('id desc')->paginate($limit);

        $this->success('请求成功', $list);
    }


    //获取附件列表
    public function getFilesList()
    {
        $id = input('customer_id');

        $files = CustomerFile::where(['customer_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }


    //获取附件列表
    public function addFiles()
    {
        $customer_id = input('customer_id');
        $files = input('files');

        $files = CustomerFile::addFiles($files, $customer_id);
        $this->success('添加成功');
    }


    //周围客户
    public function nearby()
    {
        $lng = input('lng');
        $lat = input('lat');

        //距离
        $distance = input('distance', 5, 'intval');


        if (empty($lng) && empty($lat)) {
            $this->error('参数错误');
        }

        $range = 180 / pi() * $distance / 6372.797; //里面的 1 就代表搜索 1km 之内，单位km
        $lngR = $range / cos($lat * pi() / 180);
        $maxLat = $lat + $range; //最大纬度
        $minLat = $lat - $range; //最小纬度
        $maxLng = $lng + $lngR; //最大经度
        $minLng = $lng - $lngR; //最小经度
        $where = ['lng' => ['between', [$minLng, $maxLng]], 'lat' => ['between', [$minLat, $maxLat]]];
        $params = $this->request->post();

        if (isset($params['name']['value']) && $params['name']['value']) {//客户名称
            $where['customer_name|customer_code|address|room'] = ['like', "%{$params['name']['value']}%"];
        }
        if (isset($params['level']) && $params['level']) {//客户星级
            $where['customerlevel_id'] = $params['level'];
        }
        // if (isset($params['source']) && $params['source']) {//客户来源
        //     $where['source'] = $params['source'];
        // }
        if (isset($params['follow']) && $params['follow']) {//跟进状态
            $where['follow_status'] = $params['follow'];
        }
        if (isset($params['createtime']) && $params['createtime']) {//创建时间
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'time');
            $where['createtime'] = ['between', $times];
        }

        if (isset($params['next_time']) && $params['next_time']) {//下次联系时间
            $next_time = $params['next_time'];
            $next_time = explode(',', $next_time);
            $where['next_follow_time'] = ['between', [$next_time[0], $next_time[1]]];
        }

        $whereStaff = [];
        $sale_users = $this->auth->sale_users;
        //0全部 1 我负责  2 我参与  11 我下属负责
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['staff_member_id'] = $params['staff_id'];
        } else {
            $staff_id = $this->auth->staff_member_id;
            $type = $params['type'] ?? 0;
            if ($type == 1) {//我的客户
                $whereStaff['staff_member_id'] = $staff_id;
            } elseif ($type == 11) {//下属负责的客户
                //本人存在 则剔除自己
                if (in_array($this->auth->staff_member_id,$sale_users)) {
                    $sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
                }
                $whereStaff['staff_member_id'] = ['in', $sale_users];
            } elseif ($type == 2) {//我参与的客户
                // $whereStaff = function ($query) use ($staff_id) {
                //     $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                //         ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%");
                // };
                $whereStaff['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            }else{
                // $whereStaff = function ($query) use ($staff_id) {
                //     $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                //         ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                //         ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
                // };
                $whereStaff['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            }

        }
        // if (isset($params['contract_status']) && $params['contract_status'] !== '') {
        //     $where['contract_status'] = $params['contract_status'];
        // }
        if (isset($params['is_import'])) {
            if ($params['is_import'] == 1) {
                $where['lng'] = 0;
            } elseif ($params['is_import'] == 2) {
                $where['lng'] = ['neq', 0];
            }
        }
        if (isset($params['prov']) && !empty(trim($params['prov']))) {//省市区筛选
            $prov = trim($params['prov']);
            $city = trim($params['city']);
            $area = trim($params['area']);
            $cityinfo = $prov.$city.$area;
            if (empty($city)) {
                $where['address|mergename'] = ['like', "%{$prov}%"];
            } elseif (empty($area)) {
                $where['address|mergename'] = ['like', "%{$city}%"];
            } else {
                $where['address|mergename'] = ['like', "%{$cityinfo}%"];
            }
        }
        $customers = CustomerModel::where($where)->where($whereStaff)->field('id,staff_member_id,customer_name,address,next_follow_time,lng,lat,address')
            ->with('staff')->select();
        $data = [];
        //所属员工列表
        // $myStaffIds = Staff::getMyStaffIds();
        foreach ($customers as $k => $v) {
            if ($v['staff_member_id'] == 0) {
                $v['type'] = 0;//公海
            } elseif ($v['staff_member_id'] == $this->auth->staff_member_id) {
                $v['type'] = 1;//自己的
            } elseif (in_array($v['staff_member_id'], $sale_users)) {
                $v['type'] = 2;//团队的
            } else {
                $v['type'] = 3;//其他人
            }
            $v['juli_num'] = getdistance($lng, $lat, $v['lng'], $v['lat']);
            $v['juli'] = float_number($v['juli_num']);
            $v['next_time'] = $v['next_follow_time'] > 0 ? date('Y-m-d', $v['next_follow_time']) : '无';
            $data[$v['juli_num']][] = $v;
        }
        ksort($data);

        $result = [];
        foreach ($data as $v) {
            $result = array_merge($result, array_values($v));
        }
        $this->success('请求成功', $result);
    }

    //周围客户列表
    public function nearby_customer_list()
    {
        $id = input('id');
        $page = input('page', 0);
        $limit = input('limit', 100);
        $lng = input('lng');
        $lat = input('lat');
        //我的客户
        $type = input('type');
        //距离
        $distance = input('distance', 5, 'intval');
        $name = input('name', '');

        if (empty($lng) && empty($lat)) {
            $this->error('参数错误');
        }

        $range = 180 / pi() * $distance / 6372.797; //里面的 1 就代表搜索 1km 之内，单位km
        $lngR = $range / cos($lat * pi() / 180);
        $maxLat = $lat + $range; //最大纬度
        $minLat = $lat - $range; //最小纬度
        $maxLng = $lng + $lngR; //最大经度
        $minLng = $lng - $lngR; //最小经度
        $where = ['lng' => ['between', [$minLng, $maxLng]], 'lat' => ['between', [$minLat, $maxLat]]];

        //客户分类
        if ($type == 1) {//我的客户
            $where['owner_staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//下属负责的客户
            $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
        } elseif ($type == 3) {//已成交客户
            $where['contract_status'] = 1;
        }
        //单独查询用户
        if ($id) {
            $where['id'] = $id;
        }
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }
        $customers = CustomerModel::where($where)->where([
            'lng' => [
                'neq',
                0
            ]
        ])->field('id,owner_staff_id,name,location,next_time,lng,lat,address_detail')
            ->with('ownerStaff')->select();
        $data = [];
        foreach ($customers as $k => $v) {
            $v['juli_num'] = getdistance($lng, $lat, $v['lng'], $v['lat']);
            $v['juli'] = float_number($v['juli_num']);
            $data[$v['juli']][] = $v;
        }
        ksort($data);

        $result = [];
        foreach ($data as $v) {
            $result = array_merge($result, array_values($v));
        }
        $total = count($result);
        $result = array_slice($result, $page * $limit, $limit) ?? [];
        $this->success('请求成功', ['data' => $result, 'total' => $total, 'last_page' => ceil($total / $limit)]);
    }

    // 转变 客户类型
    public function changeCustomerType()
    {
        $id = input('customer_id', '', 'intval');
        $type = input('type', '', '');
        $remark = input('remark', '');
        if (!$id) {
            $this->error('请输入客户Id!');
        }
        if (!$type || !in_array($type, $this->customerType)) {
            $this->error('请输入要转变的类型!');
        }
        if (!$remark) {
            $this->error('请输入转变原因!');
        }
        $where = [
            'id' => $id,
            'owner_staff_id' => ['in', Staff::getMyStaffIds()]
        ];
        $info = CustomerModel::where($where)->with('ownerStaff')->find();
        if (!$info) {
            $this->error('该客户不是您的客户,无法变更！');
        }
        if ($info['type'] == $type) {
            $this->error('客户原来正是' . $type . '级别！');
        }
        Db::startTrans();
        try {
            $remark = '[' . $this->auth->name . ']将客户' . $info['name'] . '从' . $info['type'] . '类型变更为' . $type . '类型【备注：' . $remark . '】';
            CustomerModel::changeCustomerType($id, $type, $remark);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

    // 员工反馈给领导
    public function feedbackToLeader()
    {
        $id = input('id', '', 'intval');
        $remark = input('remark', '');
        if (!$id || !$remark) {
            $this->error('缺少参数');
        }
        $info = Message::where('id', $id)->find();
        if (!$info) {
            $this->error('找不到此条消息');
        }

        Db::startTrans();
        try {
            StaffSignIn::createSignIn([
                'customer_id'=>$id,
                'relation_type'=>'customer',
                'relation_id'=>$id,
                'content'=>$remark,
                'staff_id'=>$this->auth->id
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

//获取客户地址
    public function getCustomerAddress()
    {
        $customer_id = input('customer_id');
        $address = CustomerModel::where(['id' => $customer_id])->field('id,address,address_detail,lng,lat')->find();
        $this->success('请求成功', $address);
    }

}
